var express = require('express');
var router = express.Router();

const User = require('./../model/user');
const MailCheck = require("./../model/mailcheck");
const {timeDifference} = require("./../utils/getTime");

const { mailSend } = require("./../utils/nodemailer")
const { createSixNum } = require("./../utils/random");

// 使用中间件来检查登录状态
const checkLogin = (req, resp, next) => {
  console.log('检查登录状态，req.session.mail', req.session.mail)
  if (req.session.mail) {
    return resp.json({
      rescode: 200,
      haslogin: true,
      mail: req.session.mail,
      msg: '您已登录',
      type: 'error'
    });
  } else {
    next();
  }
}

const checkReg = async (req, resp, next) => {
  let  mail  = req.body.mail;
  console.log(mail);
  try {
    let user = await User.findOne({
      attributes: ['email', 'pwd', 'name'],
      where: {
        email: mail
      }
    })
    if (user != null) {
      // 该邮箱已经被注册了
      resp.json({
        rescode: 200,
        hasreg: true,
        msg:'该邮箱已注册',
        type:'error',
      })
      return;
    }
  } catch (error) {
    resp.json({
      rescode:400,
      msg: error.toString()
    })
  }
  next();
}

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});


router.post('/email', checkReg);
router.post('/email', async (req, resp) => {
  let { mail } = req.body;
  let code = createSixNum();
  console.log(mail, code);
  try {
    let info = await mailSend(
      mail,
      '注册EvaluationSystem测评系统验证码',
      `<h1>${code.toString()}</h1>`
    )
    // console.log(info);
    const onemail = await MailCheck.create({
      email: mail,
      code: code
    })
    resp.json({ 
      rescode:200, 
      msg: `邮件发送成功`,
      type: 'success' 
    });
  } catch (error) {
    // console.log(error);
    resp.json({ 
      rescode:400,
      msg: error.toString(), 
    });
  }
});


router.post('/reg', checkReg);
router.post('/reg', async (req, resp) => {
  let { mail, code, pwd } = req.body;
  try {
    const oneamil = await MailCheck.findOne({
      attributes: ['updatedAt'],
      where: {
        code: code,
        email: mail
      }
    });
    console.log(oneamil == null);
    if (oneamil == null) {
      resp.json({
        rescode: 400,
        msg: '验证码错误或过期',
        type:'error'
      })
      console.log('return');
      return;
    }
    let creatTime = oneamil.updatedAt;
    // 与当前时间相比是否过期
    let currTime = new Date();
    if(!timeDifference(currTime,creatTime)){
      resp.json({
        rescode: 400,
        msg: '验证码错误或过期',
        type:'error'
      })
      return;
    }

    const user = await User.create({email:mail,pwd:pwd});
    console.log(user);
    if(user) {
      resp.json({
        rescode:200,
        msg:'注册成功',
        type:'success'
      })
    }
  } catch (error) {
    resp.json({
      rescode:400,
      msg:error.toString(),
    });
  }
});

/**
 * 登录
 */
router.post('/login', checkLogin);
router.post('/login', async (req, resp) => {
  let { mail, pwd } = req.body;
  console.log(mail, pwd);
  try {
    let user = await User.findOne({
      attributes: ['email', 'pwd', 'name'],
      where: {
        email: mail,
        pwd: pwd
      }
    })
    if (user != null) {
      req.session.mail = mail;
      resp.json({ 
        rescode:200,
        msg: '登录成功', 
        type: 'success' 
      });
    } else {
      resp.json({ 
        rescode:200,
        msg: '输入的密码错误，请重试', 
        type: 'error' 
      });
    }
  } catch (error) {
    resp.json({
      rescode: 400,
      msg: error.toString()
    })
  }
});


router.post("/haslogin", async (req, resp) => {
  console.log(req.session)
  console.log('检查登录')
  if (req.session.mail) {
    resp.json({ 
      rescode:200,
      haslogin: true,
      mail: req.session.mail 
    })
  }
  else {
    resp.json({
      rescode:200, 
      haslogin: false 
    })
  }
})


router.post("/loginout", async (req, resp) => {
  req.session.mail = null;
  resp.json({ 
    rescode:200,
    msg: '您已退出登录', 
    type: 'info' 
  })
});

module.exports = router;
